<?php
/**
 * This is Areas controller file. 
 *
 * @copyright     Copyright 2008-2010, LilCake.net
 * @link          http://lilcake.net LilCake.net
 * @package       lil
 * @subpackage    lil.controllers
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
/**
 * AreasController class
 *
 * @uses          LilAppController
 * @package       lil
 * @subpackage    lil.controllers
 */
class AreasController extends LilAppController {
/**
 * name property
 *
 * @var string 'Areas'
 */
	public $name = 'Areas';
/**
 * uses property
 *
 * @var array
 */
	public $uses = array('Lil.Area', 'Lil.AreasUser', 'Lil.User');
/**
 * beforeFilter method
 *
 * @return void
 */
	public function beforeFilter() {
		if (!empty($this->Auth)) {
			$this->Auth->allow('index', 'view', 'admin_acquire');
		}
		parent::beforeFilter();
	}
/**
 * isAuthorized method
 *
 * @return bool
 */
	public function isAuthorized() {
		if (!parent::isAuthorized()) return false;
		if (in_array($this->request->params['action'], array('index', 'view'))) return true;
		
		switch ($this->request->params['action']) {
			case 'admin_edit':
			case 'admin_delete':
			case 'admin_view':
			case 'admin_select':
				if (!empty($this->request->params['pass'][0])) {
					$assoc = Configure::read('Lil.userAssociation');
					
					// action by slug
					App::uses('Validation', 'Utility');
					$area_id = $area_id = $this->request->params['pass'][0];
					if (!is_numeric($area_id) && !Validation::uuid($area_id)) {
						$area_id = $this->Area->field('id', array(
							'Area.' . Configure::read('Lil.areaSlugField') => $area_id
						));
					}
					$ret = $this->currentUser->canAccessArea($area_id);
					return $ret;
				} else if ($this->request->params['action'] != 'admin_select') {
					// user can select no area (return to admin mode without preselected area)
					return false;
				}
				break;
			case 'admin_add':
			case 'admin_index':
				return $this->currentUser->role('admin');
				break;
			case 'admin_list':
				return true;
				break;
			default:
				return true;
		}
		return true;
	}
/**
 * index method
 *
 * @return bool
 */
	public function index() {
		if (!$areas = Configure::read('Lil.noAreas')) {
			$areas = $this->Area->find('all', array('recursive' => 0));
		}
		if (sizeof($areas) == 1) {
			$this->redirect(array(
				'plugin'     => 'lil',
				'controller' => 'areas',
				'action'     => 'index',
				'area'       => $areas[0]['Area'][Configure::read('Lil.areaSlugField')]
			));
		} else {
			$this->set(compact('areas'));
		}
	}
/**
 * view method
 *
 * @param string slug  
 * @return void
 */
	public function view($slug) {
		$this->redirect('/' . $this->request->plugin . '/' . $slug);
	}
/**
 * admin_dashboard method
 *
 * @return void
 */
	public function admin_dashboard() {
		$lang = null;
		if (isset($this->query->params['lang'])) $lang = $this->query->params['lang'];
		elseif (isset($this->query->params['named']['lang'])) $lang = $this->query->params['named']['lang'];
		
		if (!empty($lang) && in_array($lang, Configure::read('Lil.languages'))) {
			$this->Cookie->write('Lil.lang', $lang, false, '1 year');
			Configure::write('Config.language', $lang);
		}
	}
/**
 * admin_index method
 *
 * @return void
 */
	public function admin_index() {
		$this->Area->recursive = 0;
		$params = array();
		
		if (!$this->currentUser->role('admin'))
		{
			$assoc = Configure::read('Lil.userAssociation');
			$params = array(
				'conditions' => array(
					'id' => $this->AreasUser->find('list', array(
						'conditions' => array($assoc['foreignKey'] => $this->Auth->user('id')), 
						'fields'     => array('id', $assoc['associationForeignKey'])
					))
				)
			); 
		}
		
		$this->set('paginate', false);
		if (!$data = Configure::read('Lil.noAreas')) {
			App::uses('LilPluginRegistry', 'Lil.Lil'); $registry = LilPluginRegistry::getInstance();
			$params = $registry->callPluginHandlers($this, 'before_area_admin_index_params', array('params' => $params));
			$data = $this->Area->find('all', $params['params']);
		}
		
		$this->set(compact('data'));
	}
/**
 * admin_list method
 *
 * @return void
 */
	public function admin_list() {
		$this->Area->recursive = 0;
		$params = array();
		
		if (!$this->currentUser->role('admin'))
		{
			$assoc = Configure::read('Lil.userAssociation');
			$params = array(
				'conditions' => array(
					'id' => $this->AreasUser->find('list', array(
						'conditions' => array($assoc['foreignKey'] => $this->currentUser->get('id')),
						'fields'     => array('id', $assoc['associationForeignKey'])
					))
				)
			);
		}
		
		if (!$areas = Configure::read('Lil.noAreas')) {
			$params = App::uses('LilPluginRegistry', 'Lil.Lil'); $registry = LilPluginRegistry::getInstance();
			$registry->callPluginHandlers($this, 'before_area_admin_list_params', array('params' => $params));
			$areas = $this->Area->find('all', $params['params']);
		}
		
		if (sizeof($areas) == 1) {
			$this->redirect(array(
				'admin'  => true,
				'action' => 'select',
				$areas[0]['Area'][Configure::read('Lil.areaSlugField')],
			));
		}
		
		$this->set('data', $areas);
	}
/**
 * admin_select method
 *
 * This method selects area on which all operations will be performed.
 *
 * @param int $id  
 * @return void
 */
	public function admin_select($id = null) {
		if (is_null($id)) {
			$this->currentArea->clear();
			$this->setFlash(__d('lil', 'Area has been cleared.'));
			$this->redirect(array('action' => 'dashboard'));
		} else if ($this->currentArea->set($id)) {
			$this->setFlash(__d('lil', 'Area has been selected.'));
			$this->redirect(array('action' => 'dashboard'));
		} else  {
			$this->error404();
		}
	}
/**
 * admin_add method
 *
 * @return void
 */
	public function admin_add() {
		$this->setAction('admin_edit');
		$this->view = 'admin_edit';
	}
/**
 * admin_edit method
 *
 * @param int $id  
 * @return void
 */
	public function admin_edit($id = null) {
		if(!empty($this->request->data)) {
			if ($this->Area->saveAll($this->request->data)) {
				$this->setFlash(__d('lil', 'Area has been saved.'));
				return $this->doRedirect(array('action' => 'index'));
			}
			$this->setFlash(__d('lil', 'Please verify that the information is correct.'), 'error');
		} else if (!empty($id)) {
			$this->request->data = $this->Area->find(
				'first', 
				array(
					'conditions' => array('Area.id' => $id),
					'contain'    => 'User'
				)
			);
		}
		$this->setupRedirect();
		$User = ClassRegistry::init('Lil.User');
		$this->set('users', $User->find('list', array('conditions' => array('User.admin' => false))));
	}
/**
 * admin_view method
 *
 * @param int $id  
 * @return void
 */
	public function admin_view($id = null) {
		if (!empty($id) && $data = $this->Area->hasAny(array('Area.id' => $id))) {
			$data = $this->Area->find('first', array('conditions' => array('Area.id' => $id)));
			$this->set(compact('data'));
		} else {
			$this->error404();
		}
	}
/**
 * admin_delete method
 *
 * @param int $id  
 * @return void
 */
	public function admin_delete($id = null) {
		$this->Area->recursive = -1;
		if (!empty($id) && $data = $this->Area->hasAny(array('Area.id' => $id))) {
			$this->Area->delete($id);
			$this->setFlash(__d('lil', 'Area has been deleted.'));
			
			if ($id == $this->currentArea->get('id')) {
				// redirect to area selection after deleting current area
				$this->redirect(array('action' => 'list'));
			} else {
				$this->redirect(array('action' => 'index'));
			}
		} else {
			$this->error404();
		}
	}
/**
 * admin_acquire method
 *
 * @return void
 */
	public function admin_acquire() {
		$this->layout = false;
	}
}